package com.cwz.datasource.dynamic.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.cwz.core.utils.string.StringUtils;
import com.cwz.datasource.dynamic.model.DynamicUser;
import com.cwz.datasource.dynamic.utils.DataSourceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: w-demo
 * @description: 动态数据源初始类
 * @author: Wen
 **/
@Configuration
public class DynamicDataSourceInit {
	@Autowired
	private DefaultDataSourceProperties defaultDataSourceProperties;
	@Autowired
	private DynamicRoutingDataSource dynamicRoutingDataSource;

	@PostConstruct
	public void init() {
		Map<Object, Object> targetDataSources = dynamicRoutingDataSource.getTargetDataSources();
		DruidDataSource baseDatasource = (DruidDataSource) targetDataSources.get("baseDatasource");
		Connection conn = null;
		try {
			conn = baseDatasource.getConnection();
			List<DynamicUser> dynamicUser = getDynamicUser(conn, null);
			for (DynamicUser user : dynamicUser) {
				DruidDataSource druidDataSource = new DruidDataSource();
				DataSourceUtils.setDruidDataSource(druidDataSource, defaultDataSourceProperties);
				druidDataSource.setUrl(user.getDbUrl());
				targetDataSources.put(user.getCompany(), druidDataSource);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		dynamicRoutingDataSource.setTargetDataSources(targetDataSources);
		dynamicRoutingDataSource.afterPropertiesSet();
	}

	public List<DynamicUser> getDynamicUser(Connection conn, String company) {
		// 1.准备返回容器
		List<DynamicUser> resultList = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			// 2.编写sql语句
			// TODO: 2023/7/5 这里要把以后的具体某个 sql 语句给写上
			StringBuilder sb = new StringBuilder();
			sb.append("select company, db_url from sys_company where is_delete = 0");
			if (StringUtils.isNotBlank(company)) {
				sb.append(" and company = ?");
			}
			sb.append(" order by id asc");
			// 3.获取sql预编译对象
			ps = conn.prepareStatement(sb.toString());
			// 4.设置参数给占位符
			if (StringUtils.isNotBlank(company)) {
				ps.setString(1, company);
			}
			// 5.执行并保存结果集
			rs = ps.executeQuery();
			// 6.处理结果集
			Map<String, DynamicUser> resultMap = new HashMap<>(16);
			while (rs.next()) {
				if (StringUtils.isNull(resultMap.get(rs.getString("company")))) {
					DynamicUser dynamicUser = new DynamicUser();
					dynamicUser.setCompany(rs.getString("company"));
					dynamicUser.setDbUrl(rs.getString("db_url"));
					resultMap.put(dynamicUser.getCompany(), dynamicUser);
				}
			}
			// 封装成List返回
			resultList = new ArrayList<>(resultMap.values());
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 释放连接资源
			DataSourceUtils.release(conn, ps, rs);
		}
		return resultList;
	}
}
